package com.znsd.zl.sys.oss.controller;

import com.znsd.zl.exception.RRException;
import com.znsd.zl.sys.oss.cloud.OSSFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * <p>
 *      oss文件上传外部接口
 * </p>
 *
 * @ClassName FileUploadController
 * @Description 文件上传控制器
 * @Author jaypdd
 * @Date 2020/8/24 9:27
 * @Version v1.0
 */
@Slf4j
@RestController
@RequestMapping("/app")
public class OssFileController {

	/**
	 * 传递字节数组将文件上传到oss服务器
	 * @param data  字节数组
	 * @param suffix 后缀
	 */
	@PostMapping("/byteFileUpload")
	public String feignByteUpload(@RequestParam("suffix") String suffix, @RequestBody byte[] data) {
		String url = null;
		url = OSSFactory.build().uploadSuffix(data, suffix);
		log.info("oss 文件上传成功=====>{}" + url);
		return url;
	}

	/**
	 * multipart/form-data表单类型MultipartFile对象文件上传
	 * @param file  文件对象
	 * @return 返回服务器文件位置url
	 */
	@PostMapping(value = "/feignUpload")
	public String feignUpload(@RequestPart MultipartFile file){
		if (file.isEmpty()) {
			throw new RRException("上传文件不能为空");
		}

		//上传文件
		String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
		String url = null;
		try {
			url = OSSFactory.build().uploadSuffix(file.getBytes(), suffix);
		} catch (IOException e) {
			e.printStackTrace();
			log.error("文件上传失败===>{}", file);
		}

		log.info("oss 文件上传成功=====>{}" + url);
		return url;
	}

}
